//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import s from "./ProjectHome.module.less";
import { observer } from 'mobx-react';
import { Button, Card, Form, Input, List, Menu, Select, Space, Switch } from "antd";
import { useStores } from "@/hooks";
import {
    list as list_entry,
    ENTRY_TYPE_SPRIT, ENTRY_TYPE_DOC, ENTRY_TYPE_PAGES,
    ENTRY_TYPE_API_COLL,
    ENTRY_TYPE_DRAW,
    ENTRY_TYPE_DATAVIEW,
    ENTRY_TYPE_KNOWLEDGE,
    type ENTRY_TYPE
} from "@/api/project_entry";
import { request } from "@/utils/request";
import { FilterTwoTone } from "@ant-design/icons";
import EntryCard from "./EntryCard";
import { listen } from '@tauri-apps/api/event';
import type * as NoticeType from '@/api/notice_type';
import ProjectDataViewList from "@/pages/DataView/ProjectDataViewList";
import EditProjectViewModal from "@/pages/DataView/compoents/EditProjectViewModal";
import { PROJECT_HOME_CONTENT_LIST } from "@/api/project";
import { useTranslation } from "react-i18next";

const PAGE_SIZE = 24;

const ProjectHome = () => {
    const { t } = useTranslation();

    const userStore = useStores("userStore");
    const projectStore = useStores("projectStore");
    const entryStore = useStores("entryStore");

    const [activeKey, setActiveKey] = useState<"workplan" | "knowledge" | "dataview">("workplan");
    const [dataVersion, setDataVersion] = useState(0); //防止两次加载
    const [subEntryType, setSubEntryType] = useState(ENTRY_TYPE_KNOWLEDGE);

    const [projectViewVersion, setProjectViewVersion] = useState(0);
    const [showAddProjectViewModal, setShowAddProjectViewModal] = useState(false);

    const loadEntryList = async () => {
        if (projectStore.curProjectId == "") {
            entryStore.entryList = [];
            return;
        }

        let entryTypeList: ENTRY_TYPE[] = [];
        if (projectStore.projectHome.contentEntryType == ENTRY_TYPE_SPRIT) {
            entryTypeList = [ENTRY_TYPE_SPRIT];
        } else {
            if (subEntryType == ENTRY_TYPE_KNOWLEDGE) {
                entryTypeList = [ENTRY_TYPE_DOC, ENTRY_TYPE_PAGES, ENTRY_TYPE_API_COLL, ENTRY_TYPE_DRAW];
            } else {
                entryTypeList = [subEntryType];
            }
        }

        const listParam = {
            filter_by_watch: projectStore.projectHome.contentFilterByWatch,
            filter_by_tag_id: projectStore.projectHome.contentTagIdList.length > 0,
            tag_id_list: projectStore.projectHome.contentTagIdList,
            filter_by_keyword: projectStore.projectHome.contentKeyword.length > 0,
            keyword: projectStore.projectHome.contentKeyword,
            filter_by_entry_type: true,
            entry_type_list: entryTypeList,
        };

        if (projectStore.curProjectId == "") {
            projectStore.projectHome.contentTotalCount = 0;
            entryStore.entryList = [];
            return;
        }

        const res = await request(list_entry({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            list_param: listParam,
            offset: PAGE_SIZE * projectStore.projectHome.contentCurPage,
            limit: PAGE_SIZE,
        }));
        projectStore.projectHome.contentTotalCount = res.total_count;
        entryStore.entryList = res.entry_list;
    };

    const entryItemList = (
        <List rowKey="entry_id" dataSource={entryStore.entryList} grid={{ gutter: 16 }}
            renderItem={item => (
                <List.Item key={item.entry_id}>
                    <EntryCard entryInfo={item} />
                </List.Item>
            )} pagination={{ total: projectStore.projectHome.contentTotalCount, current: projectStore.projectHome.contentCurPage + 1, pageSize: PAGE_SIZE, onChange: page => projectStore.projectHome.contentCurPage = page - 1, hideOnSinglePage: true }} />
    );

    const resetParamAndIncVersion = () => {
        if (projectStore.projectHome.contentCurPage != 0) {
            projectStore.projectHome.contentCurPage = 0;
        }
        if (projectStore.projectHome.contentKeyword != "") {
            projectStore.projectHome.contentKeyword = "";
        }
        if (projectStore.projectHome.contentTagIdList.length != 0) {
            projectStore.projectHome.contentTagIdList = [];
        }
        setDataVersion(oldValue => oldValue + 1);
    };

    useEffect(() => {
        resetParamAndIncVersion();
    }, [projectStore.curProjectId, projectStore.projectHome.contentEntryType]);

    useEffect(() => {
        loadEntryList();
    }, [projectStore.projectHome.contentCurPage, dataVersion, projectStore.projectHome.contentKeyword, projectStore.projectHome.contentTagIdList, projectStore.projectHome.contentEntryType, projectStore.projectHome.contentFilterByWatch, subEntryType]);

    useEffect(() => {
        if (projectStore.projectHome.homeType == PROJECT_HOME_CONTENT_LIST) {
            if (projectStore.projectHome.contentEntryType == ENTRY_TYPE_SPRIT) {
                setActiveKey("workplan");
            } else if (projectStore.projectHome.contentEntryType == ENTRY_TYPE_KNOWLEDGE) {
                setActiveKey("knowledge");
            } else if (projectStore.projectHome.contentEntryType == ENTRY_TYPE_DATAVIEW) {
                setActiveKey("dataview");
            }
        }
    }, [projectStore.projectHome.homeType, projectStore.projectHome.contentEntryType]);

    useEffect(() => {
        const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
            const notice = ev.payload;
            if (notice.EntryNotice?.NewEntryNotice !== undefined && notice.EntryNotice.NewEntryNotice.project_id == projectStore.curProjectId && notice.EntryNotice.NewEntryNotice.create_user_id == userStore.userInfo.userId) {
                resetParamAndIncVersion();
            }
        });
        return () => {
            unListenFn.then((unListen) => unListen());
        };
    }, []);

    return (
        <div className={s.home_wrap}>
            <Card title={
                <Menu mode="horizontal" style={{ border: "none" }}
                    selectedKeys={[activeKey]} items={[
                        {
                            label: t("project.home.workPlan", { shortCut: "" }),
                            key: `workplan`,
                            title: t("project.home.workPlan", { shortCut: "(alt+1)" }),
                            style: {
                                fontSize: "20px",
                                fontWeight: 700,
                            }
                        },
                        {
                            label: t("project.home.knowledgeBase", { shortCut: "" }),
                            key: `knowledge`,
                            title: t("project.home.knowledgeBase", { shortCut: "(alt+2)" }),
                            style: {
                                fontSize: "20px",
                                fontWeight: 700,
                            }
                        },
                        {
                            label: t("project.home.dataView", { shortCut: "" }),
                            key: `dataview`,
                            title: t("project.home.dataView", { shortCut: "(alt+3)" }),
                            style: {
                                fontSize: "20px",
                                fontWeight: 700,
                            }
                        },
                    ]} onSelect={info => {
                        if (info.selectedKeys.length == 0) {
                            return;
                        }
                        if (info.selectedKeys[0] == activeKey) {
                            return;
                        }
                        if (info.selectedKeys[0] == "workplan") {
                            projectStore.projectHome.homeType = PROJECT_HOME_CONTENT_LIST;
                            projectStore.projectHome.contentEntryType = ENTRY_TYPE_SPRIT;
                        } else if (info.selectedKeys[0] == "knowledge") {
                            projectStore.projectHome.homeType = PROJECT_HOME_CONTENT_LIST;
                            projectStore.projectHome.contentEntryType = ENTRY_TYPE_KNOWLEDGE;
                        } else if (info.selectedKeys[0] == "dataview") {
                            projectStore.projectHome.homeType = PROJECT_HOME_CONTENT_LIST;
                            projectStore.projectHome.contentEntryType = ENTRY_TYPE_DATAVIEW;
                        }
                    }} />
            }
                headStyle={{ paddingLeft: "0px" }} bodyStyle={{ padding: "4px 0px" }}
                bordered={false} extra={
                    <Space size="small">
                        {projectStore.projectHome.homeType == PROJECT_HOME_CONTENT_LIST && projectStore.projectHome.contentEntryType == ENTRY_TYPE_SPRIT && (
                            <Button type="primary" onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                entryStore.createEntryType = ENTRY_TYPE_SPRIT;
                            }} disabled={projectStore.isClosed || !projectStore.isAdmin}>{t("text.create")}</Button>
                        )}
                        {projectStore.projectHome.homeType == PROJECT_HOME_CONTENT_LIST && [ENTRY_TYPE_SPRIT, ENTRY_TYPE_DATAVIEW].includes(projectStore.projectHome.contentEntryType) == false && (
                            <Button type="primary" onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                entryStore.createEntryType = ENTRY_TYPE_DOC;
                            }} disabled={projectStore.isClosed}>{t("text.create")}</Button>
                        )}
                        {projectStore.projectHome.homeType == PROJECT_HOME_CONTENT_LIST && projectStore.projectHome.contentEntryType == ENTRY_TYPE_DATAVIEW && (
                            <Button type="primary" onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setShowAddProjectViewModal(true);
                            }} disabled={projectStore.isClosed}>{t("text.create")}</Button>
                        )}
                    </Space>
                }>
                {projectStore.projectHome.homeType == PROJECT_HOME_CONTENT_LIST && (
                    <Card bordered={false}
                        headStyle={{ backgroundColor: "#fafafa", height: [ENTRY_TYPE_DATAVIEW].includes(projectStore.projectHome.contentEntryType) ? "0px" : "44px" }}
                        bodyStyle={{ height: [ENTRY_TYPE_DATAVIEW].includes(projectStore.projectHome.contentEntryType) ? "calc(100vh - 170px)" : "calc(100vh - 210px)", overflowY: "scroll", overflowX: "hidden" }}
                        extra={[ENTRY_TYPE_DATAVIEW].includes(projectStore.projectHome.contentEntryType) ? undefined : (
                            <>
                                {[ENTRY_TYPE_DATAVIEW].includes(projectStore.projectHome.contentEntryType) == false && (
                                    <Form layout="inline">
                                        <FilterTwoTone style={{ fontSize: "24px", marginRight: "10px" }} />
                                        {projectStore.projectHome.contentEntryType == ENTRY_TYPE_KNOWLEDGE && (
                                            <Form.Item>
                                                <Select value={subEntryType} onChange={value => setSubEntryType(value)} style={{ width: "100px" }}>
                                                    <Select.Option value={ENTRY_TYPE_KNOWLEDGE}>{t("text.all")}</Select.Option>
                                                    <Select.Option value={ENTRY_TYPE_DOC}>{t("project.entry.type.doc")}</Select.Option>
                                                    <Select.Option value={ENTRY_TYPE_DRAW}>{t("project.entry.type.draw")}</Select.Option>
                                                    <Select.Option value={ENTRY_TYPE_API_COLL}>{t("project.entry.type.apiColl")}</Select.Option>
                                                    <Select.Option value={ENTRY_TYPE_PAGES}>{t("project.entry.type.pages")}</Select.Option>
                                                </Select>
                                            </Form.Item>
                                        )}
                                        <Form.Item>
                                            <Input style={{ width: "140px" }} value={projectStore.projectHome.contentKeyword} onChange={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                projectStore.projectHome.contentKeyword = e.target.value.trim();
                                            }} allowClear placeholder={t("project.entry.inputKeywordTip")} />
                                        </Form.Item>
                                        {(projectStore.curProject?.tag_list ?? []).filter(item => item.use_in_entry).length > 0 && (
                                            <Form.Item>
                                                <Select mode="multiple" style={{ minWidth: "100px" }}
                                                    allowClear value={projectStore.projectHome.contentTagIdList} onChange={value => projectStore.projectHome.contentTagIdList = value}
                                                    placeholder={t("project.entry.selectTagTip")}>
                                                    {(projectStore.curProject?.tag_list ?? []).filter(item => item.use_in_entry).map(item => (
                                                        <Select.Option key={item.tag_id} value={item.tag_id}>
                                                            <div style={{ backgroundColor: item.bg_color, padding: "0px 4px" }}>{item.tag_name}</div></Select.Option>
                                                    ))}
                                                </Select>
                                            </Form.Item>
                                        )}
                                        <Form.Item label={t("text.myWatch")} style={{ marginRight: "0px" }}>
                                            <Switch checked={projectStore.projectHome.contentFilterByWatch} onChange={value => projectStore.projectHome.contentFilterByWatch = value} />
                                        </Form.Item>
                                    </Form>
                                )}
                            </>
                        )}>
                        {[ENTRY_TYPE_DATAVIEW].includes(projectStore.projectHome.contentEntryType) == false && (<>{entryItemList}</>)}
                        {projectStore.projectHome.contentEntryType == ENTRY_TYPE_DATAVIEW && (
                            <ProjectDataViewList dataVersion={projectViewVersion} projectId={projectStore.curProjectId} />
                        )}
                    </Card>
                )}
            </Card>
            {showAddProjectViewModal && (
                <EditProjectViewModal onCancel={() => setShowAddProjectViewModal(false)} onOk={() => {
                    setShowAddProjectViewModal(false);
                    setProjectViewVersion(projectViewVersion + 1);
                }} />
            )}
        </div >
    );
};

export default observer(ProjectHome);